<?php
// 【最终完整版】m-merchant/do_set_commission.php
header('Content-Type: application/json; charset=utf-8');

function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%';
    if (!$token) return null; $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null; list($h, $p, $s) = $token_parts;
    $sig = base64_decode(str_replace(['-','_'],['+','/'], $s));
    $exp_sig = hash_hmac('sha256', $h.".".$p, $secret_key, true);
    if (!hash_equals($exp_sig, $sig)) return null;
    $payload = json_decode(base64_decode(str_replace(['-','_'],['+','/'], $p)), true);
    if ($payload === null || ($payload['exp']??0) < time()) return null;
    return $payload['data'];
}
function get_authorization_header() {
    if (isset($_SERVER['Authorization'])) return trim($_SERVER["Authorization"]);
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) return trim($_SERVER["HTTP_AUTHORIZATION"]);
    if (function_exists('getallheaders')) {
        $h = getallheaders(); if (isset($h['Authorization'])) return trim($h['Authorization']);
    } return null;
}
$user_data = verify_token(str_replace('Bearer ', '', get_authorization_header()));
if ($user_data === null) { http_response_code(401); echo json_encode(['status' => -99, 'msg' => '登录失效']); exit(); }

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$response = ['status' => -1, 'msg' => '无效的请求'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $proxy_acc_safe = mysqli_real_escape_string($con, $user_data['proxy_acc']);
    $type = (int)($_POST['commission_type'] ?? 0);
    $value = (float)($_POST['commission_value'] ?? 0.00);

    $sql = "UPDATE proxy SET commission_type = ?, commission_value = ? WHERE proxy_acc = ?";
    $stmt = mysqli_prepare($con, $sql);
    mysqli_stmt_bind_param($stmt, "ids", $type, $value, $proxy_acc_safe);
    
    if (mysqli_stmt_execute($stmt)) {
        if (mysqli_stmt_affected_rows($stmt) > 0) {
            $response = ['status' => 0, 'msg' => '全局抽成规则已成功保存！'];
        } else {
            $response = ['status' => 1, 'msg' => '规则未发生变化，无需保存。'];
        }
    } else {
        $response['msg'] = '数据库更新失败，请重试。';
    }
    mysqli_stmt_close($stmt);
}
echo json_encode($response);
mysqli_close($con);
?>